package com.information.controller;

import com.backend.entity.User;
import com.backend.service.IpBlacklistService;
import com.backend.service.UserService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.core.io.Resource;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public ResponseEntity<List<User>> getAllUsers(HttpServletRequest request) {
        try {
            String operatedBy = getOperator(request);
            
            // 获取当前操作者信息
            User operator = userService.findUserByUsername(operatedBy).orElse(null);
            Long currentUserId = operator != null ? operator.getId() : null;
            

            // 如果找不到操作者，记录详细信息
            if (operator == null) {
                System.err.println("警告：无法找到操作者用户信息，用户名: " + operatedBy);
            }
            
            List<User> users = userService.findAllUsers();
            
            if (operator.getRole().name().equals("USER")) {
                // 对用户列表进行脱敏处理，但当前用户自己的信息不脱敏
                List<User> processedUsers = users.stream()
                        .map(user -> {
                            // 使用用户名进行比较，因为ID可能为null
                            boolean isSelf = operatedBy != null && operatedBy.equals(user.getUsername());

                            if (isSelf) {
                                // 自己的信息不脱敏，但清除密码
                                User selfUser = new User();
                                selfUser.setId(user.getId());
                                selfUser.setUsername(user.getUsername());
                                selfUser.setName(user.getName());
                                selfUser.setEmail(user.getEmail()); // 不脱敏
                                selfUser.setPhone(user.getPhone()); // 不脱敏
                                selfUser.setAge(user.getAge());
                                selfUser.setGender(user.getGender());
                                selfUser.setAddress(user.getAddress());
                                selfUser.setRole(user.getRole());
                                selfUser.setIsDelete(user.getIsDelete());
                                selfUser.setStatus(user.getStatus());
                                selfUser.setCreatedAt(user.getCreatedAt());
                                selfUser.setUpdatedAt(user.getUpdatedAt());
                                selfUser.setPassword(null); // 密码不返回

                                return selfUser;
                            } else {
                                // 他人信息进行脱敏
                                User maskedUser = com.backend.utils.SensitiveDataUtil.maskSensitiveDataByUsername(user, operatedBy);
                                return maskedUser;
                            }
                        })
                        .collect(java.util.stream.Collectors.toList());
                return ResponseEntity.ok(processedUsers);
            }
            return ResponseEntity.ok(users);
        } catch (Exception e) {
            System.err.println("获取用户列表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id, HttpServletRequest request) {
        try {
            String operatedBy = getOperator(request);
            
            // 获取当前操作者信息
            User operator = userService.findUserByUsername(operatedBy).orElse(null);
            
            Optional<User> userOpt = userService.findUserById(id);
            if (userOpt.isPresent()) {
                User user = userOpt.get();
                
                // 如果查看的是自己的信息，不进行脱敏
                if (operator != null && operator.getId().equals(id)) {
                    // 创建副本并清除密码字段但保留其他敏感信息
                    User selfUser = new User();
                    selfUser.setId(user.getId());
                    selfUser.setUsername(user.getUsername());
                    selfUser.setName(user.getName());
                    selfUser.setEmail(user.getEmail()); // 不脱敏
                    selfUser.setPhone(user.getPhone()); // 不脱敏
                    selfUser.setAge(user.getAge());
                    selfUser.setGender(user.getGender());
                    selfUser.setAddress(user.getAddress());
                    selfUser.setRole(user.getRole());
                    selfUser.setIsDelete(user.getIsDelete());
                    selfUser.setStatus(user.getStatus());
                    selfUser.setCreatedAt(user.getCreatedAt());
                    selfUser.setUpdatedAt(user.getUpdatedAt());
                    selfUser.setPassword(null); // 密码不返回
                    
                    return ResponseEntity.ok(selfUser);
                } else {
                    // 查看他人信息时进行脱敏
                    Long currentUserId = operator != null ? operator.getId() : null;
                    User maskedUser = com.backend.utils.SensitiveDataUtil.maskSensitiveData(user, currentUserId);
                    return ResponseEntity.ok(maskedUser);
                }
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            System.err.println("获取用户失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @PostMapping
    public ResponseEntity<?> createUser(@RequestBody User user, HttpServletRequest request) {
        try {

            if (userService.existsByUsername(user.getUsername())) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "用户名已存在，请更换其他用户名");
                return ResponseEntity.status(HttpStatus.CONFLICT).body(errorResponse);
            }

            // 获取当前操作人的用户名，如果是未登录的初始状态，可能使用默认操作人
            String operatedBy = getOperator(request);

            // 清空ID，确保是新建而不是更新
            user.setId(null);

            // 调用服务层处理用户创建
            User newUser = userService.saveUser(user, operatedBy);

            return ResponseEntity.status(HttpStatus.CREATED).body(newUser);
        } catch (Exception e) {
            System.err.println("创建用户时发生错误: " + e.getMessage());
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "创建用户失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updateUser(@PathVariable Long id, @RequestBody User userDetails,
                                        HttpServletRequest request) {
        try {
            String operatedBy = getOperator(request);

            // 获取操作者信息进行权限检查
            User operator = userService.findUserByUsername(operatedBy)
                    .orElseThrow(() -> new RuntimeException("操作者未找到: " + operatedBy));

            // 检查是否有权限操作目标用户
            if (!userService.canOperateOnUser(operator.getId(), operator.getRole().name(), id)) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "权限不足：无法操作此用户");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorResponse);
            }

            User updatedUser = userService.updateUser(id, userDetails, operatedBy);
            return ResponseEntity.ok(updatedUser);
        } catch (RuntimeException e) {
            if (e.getMessage().contains("权限不足")) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", e.getMessage());
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorResponse);
            }
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable Long id, HttpServletRequest request) {
        try {
            String operatedBy = getOperator(request);

            // 获取操作者信息进行权限检查
            User operator = userService.findUserByUsername(operatedBy)
                    .orElseThrow(() -> new RuntimeException("操作者未找到: " + operatedBy));

            // 检查是否有权限操作目标用户
            if (!userService.canOperateOnUser(operator.getId(), operator.getRole().name(), id)) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "权限不足：无法操作此用户");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorResponse);
            }

            userService.deleteUser(id, operatedBy);
            return ResponseEntity.noContent().build();
        } catch (RuntimeException e) {
            if (e.getMessage().contains("权限不足")) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", e.getMessage());
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorResponse);
            }
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> loginRequest,
                                   HttpServletRequest request) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");

        // 获取客户端IP地址
        String clientIp = getClientIpAddress(request);

        // 检查IP是否在黑名单中
        boolean isBlacklisted = ipBlacklistService.isBlacklisted(clientIp);

        if (isBlacklisted) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "IP已被添加到黑名单，请联系管理员");
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorResponse);
        }

        // 原有的登录逻辑继续...
        if (username == null || password == null) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "用户名和密码不能为空");
            return ResponseEntity.badRequest().body(errorResponse);
        }

        return userService.login(username, password)
                .map(user -> {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", true);
                    response.put("message", "Login successful");
                    response.put("userId", user.getId());
                    response.put("username", user.getUsername());
                    response.put("role", user.getRole().name());

                    // 登录成功时返回用户完整信息（不脱敏）
                    User userInfo = new User();
                    userInfo.setId(user.getId());
                    userInfo.setUsername(user.getUsername());
                    userInfo.setName(user.getName());
                    userInfo.setEmail(user.getEmail()); // 不脱敏
                    userInfo.setPhone(user.getPhone()); // 不脱敏
                    userInfo.setAge(user.getAge());
                    userInfo.setGender(user.getGender());
                    userInfo.setAddress(user.getAddress());
                    userInfo.setRole(user.getRole());
                    userInfo.setStatus(user.getStatus());
                    userInfo.setCreatedAt(user.getCreatedAt());
                    userInfo.setUpdatedAt(user.getUpdatedAt());
                    // 密码不返回
                    userInfo.setPassword(null);

                    response.put("userInfo", userInfo);

                    return ResponseEntity.ok(response);
                })
                .orElseGet(() -> {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", false);
                    response.put("message", "Invalid username or password");
                    return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
                });
    }
    @Autowired
    private IpBlacklistService ipBlacklistService;

    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        String xRealIp = request.getHeader("X-Real-IP");
        String remoteAddr = request.getRemoteAddr();

        // 详细日志记录所有IP信息

        String clientIp = null;
        if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
            clientIp = xForwardedFor.split(",")[0].trim();
        } else if (xRealIp != null && !xRealIp.isEmpty()) {
            clientIp = xRealIp;
        } else {
            clientIp = remoteAddr;
        }
        return clientIp;
    }

    @PutMapping("/{id}/status")
    public ResponseEntity<?> updateUserStatus(@PathVariable Long id,
                                              @RequestBody Map<String, String> statusRequest,
                                              HttpServletRequest request) {
        try {
            String newStatus = statusRequest.get("status");
            String operatedBy = getOperator(request);

            // 获取操作者信息进行权限检查
            User operator = userService.findUserByUsername(operatedBy)
                    .orElseThrow(() -> new RuntimeException("操作者未找到: " + operatedBy));

            // 检查是否有权限操作目标用户
            if (!userService.canOperateOnUser(operator.getId(), operator.getRole().name(), id)) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "权限不足：无法操作此用户");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorResponse);
            }

            User updatedUser = userService.updateUserStatus(id, newStatus, operatedBy);
            return ResponseEntity.ok(updatedUser);
        } catch (RuntimeException e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    @GetMapping("/template")
    public ResponseEntity<Resource> downloadTemplate(HttpServletRequest request) {
        try {
            String operatedBy = getOperator(request);

            // 创建Excel模板
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("用户导入模板");

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"用户名*", "密码*", "姓名", "邮箱", "电话", "年龄", "性别", "地址", "角色*"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 创建示例数据行
            Row exampleRow = sheet.createRow(1);
            String[] examples = {"zhangsan", "123456", "张三", "zhangsan@example.com", "13800138000", "25", "男", "北京市朝阳区", "USER"};
            for (int i = 0; i < examples.length; i++) {
                Cell cell = exampleRow.createCell(i);
                cell.setCellValue(examples[i]);
            }

            // 添加说明行
            Row noteRow = sheet.createRow(21);
            Cell noteCell = noteRow.createCell(0);
            noteCell.setCellValue("说明：带*为必填项，角色可选值：USER/ADMIN/SUPER_ADMIN，性别可选值：男/女");
            Cell noteCellTwo = exampleRow.createCell(9);
            noteCellTwo.setCellValue("注意：第一行为示例，不实际导入！");

            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

            // 写入临时文件
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            workbook.close();

            ByteArrayResource resource = new ByteArrayResource(outputStream.toByteArray());

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"用户导入模板.xlsx\"")
                    .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                    .body(resource);

        } catch (Exception e) {
            System.err.println("生成模板失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @PostMapping("/import")
    public ResponseEntity<?> importUsers(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        try {
            String operatedBy = getOperator(request);

            if (file.isEmpty()) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "请选择要上传的文件");
                return ResponseEntity.badRequest().body(errorResponse);
            }

            // 调用服务层处理Excel导入
            Map<String, Integer> result = userService.importUsersFromExcel(file, operatedBy);

            Map<String, Object> response = new HashMap<>();
            response.put("successCount", result.get("success"));
            response.put("failCount", result.get("fail"));
            response.put("message", "导入完成");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            System.err.println("导入用户失败: " + e.getMessage());
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "导入失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    @GetMapping("/export")
    public ResponseEntity<Resource> exportUsers(HttpServletRequest request) {
        try {
            String operatedBy = getOperator(request);

            // 权限检查：只有管理员和超级管理员可以导出
            User operator = userService.findUserByUsername(operatedBy)
                    .orElseThrow(() -> new RuntimeException("操作者未找到: " + operatedBy));

            if (operator.getRole() != User.UserRole.ADMIN && operator.getRole() != User.UserRole.SUPER_ADMIN) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }

            List<User> users = userService.findAllUsers();
            
            // 对敏感信息进行脱敏处理
            List<User> maskedUsers = com.backend.utils.SensitiveDataUtil.maskSensitiveDataList(users, operator.getId());

            // 创建Excel工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("用户数据");

            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"ID", "用户名", "姓名", "邮箱", "电话", "年龄", "性别", "地址", "角色", "状态"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 填充数据
            int rowNum = 1;
            for (User user : maskedUsers) {
                Row dataRow = sheet.createRow(rowNum++);
                dataRow.createCell(0).setCellValue(user.getId());
                dataRow.createCell(1).setCellValue(user.getUsername());
                dataRow.createCell(2).setCellValue(user.getName() != null ? user.getName() : "");
                dataRow.createCell(3).setCellValue(user.getEmail() != null ? user.getEmail() : "");
                dataRow.createCell(4).setCellValue(user.getPhone() != null ? user.getPhone() : "");
                dataRow.createCell(5).setCellValue(user.getAge() != null ? user.getAge() : 0);
                dataRow.createCell(6).setCellValue(user.getGender() != null ? user.getGender() : "");
                dataRow.createCell(7).setCellValue(user.getAddress() != null ? user.getAddress() : "");
                dataRow.createCell(8).setCellValue(getRoleDisplayName(user.getRole()));
                dataRow.createCell(9).setCellValue(getStatusDisplayName(user.getStatus()));
            }

            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
                // 设置最小列宽
                if (sheet.getColumnWidth(i) < 2000) {
                    sheet.setColumnWidth(i, 2000);
                }
                // 设置最大列宽
                if (sheet.getColumnWidth(i) > 8000) {
                    sheet.setColumnWidth(i, 8000);
                }
            }

            // 写入字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            workbook.close();

            ByteArrayResource resource = new ByteArrayResource(outputStream.toByteArray());

            // 生成文件名
            String timestamp = java.time.LocalDateTime.now()
                    .format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd_HHmm"));
            String filename = "用户数据导出_" + timestamp + ".xlsx";

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
                    .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                    .body(resource);

        } catch (Exception e) {
            System.err.println("导出用户数据失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @GetMapping("/deleted")
    public ResponseEntity<List<User>> getDeletedUsers(HttpServletRequest request) {
        try {
            String operatedBy = getOperator(request);

            // 权限检查：只有管理员和超级管理员可以查看回收站
            User operator = userService.findUserByUsername(operatedBy)
                    .orElseThrow(() -> new RuntimeException("操作者未找到: " + operatedBy));

            if (operator.getRole() != User.UserRole.ADMIN && operator.getRole() != User.UserRole.SUPER_ADMIN) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }

            List<User> deletedUsers = userService.findDeletedUsers();
            
            // 对敏感信息进行脱敏处理
            List<User> maskedUsers = com.backend.utils.SensitiveDataUtil.maskSensitiveDataList(deletedUsers, operator.getId());
            
            return ResponseEntity.ok(maskedUsers);

        } catch (Exception e) {
            System.err.println("获取已删除用户失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @PutMapping("/{id}/restore")
    public ResponseEntity<?> restoreUser(@PathVariable Long id, HttpServletRequest request) {
        try {
            String operatedBy = getOperator(request);

            // 权限检查
            User operator = userService.findUserByUsername(operatedBy)
                    .orElseThrow(() -> new RuntimeException("操作者未找到: " + operatedBy));

            if (operator.getRole() != User.UserRole.ADMIN && operator.getRole() != User.UserRole.SUPER_ADMIN) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "权限不足：无法恢复用户");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorResponse);
            }

            User restoredUser = userService.restoreUser(id, operatedBy);
            return ResponseEntity.ok(restoredUser);

        } catch (RuntimeException e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    @DeleteMapping("/{id}/permanent")
    public ResponseEntity<?> permanentDeleteUser(@PathVariable Long id, HttpServletRequest request) {
        try {
            String operatedBy = getOperator(request);

            // 权限检查
            User operator = userService.findUserByUsername(operatedBy)
                    .orElseThrow(() -> new RuntimeException("操作者未找到: " + operatedBy));

            if (operator.getRole() != User.UserRole.ADMIN && operator.getRole() != User.UserRole.SUPER_ADMIN) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "权限不足：无法彻底删除用户");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorResponse);
            }

            userService.permanentDeleteUser(id, operatedBy);
            return ResponseEntity.noContent().build();

        } catch (RuntimeException e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    @DeleteMapping("/recycle-bin/clear")
    public ResponseEntity<?> clearRecycleBin(HttpServletRequest request) {
        try {
            String operatedBy = getOperator(request);

            // 权限检查：只有超级管理员可以清空回收站
            User operator = userService.findUserByUsername(operatedBy)
                    .orElseThrow(() -> new RuntimeException("操作者未找到: " + operatedBy));

            if (operator.getRole() != User.UserRole.SUPER_ADMIN) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "权限不足：只有超级管理员可以清空回收站");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorResponse);
            }

            int deletedCount = userService.clearRecycleBin(operatedBy);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "回收站已清空");
            response.put("deletedCount", deletedCount);
            return ResponseEntity.ok(response);

        } catch (RuntimeException e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    /**
     * 获取角色显示名称
     */
    private String getRoleDisplayName(User.UserRole role) {
        if (role == null) return "未知";
        switch (role) {
            case SUPER_ADMIN: return "超级管理员";
            case ADMIN: return "管理员";
            case USER: return "普通用户";
            default: return "未知";
        }
    }

    /**
     * 获取状态显示名称
     */
    private String getStatusDisplayName(User.UserStatus status) {
        if (status == null) return "未知";
        switch (status) {
            case ACTIVE: return "激活";
            case INACTIVE: return "禁用";
            case LOCKED: return "锁定";
            default: return "未知";
        }
    }

    /**
     * 格式化日期时间
     */
    private String formatDateTime(java.time.LocalDateTime dateTime) {
        if (dateTime == null) return "";
        return dateTime.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 获取当前操作人
     * @param request
     * @return String
     */
    private String getOperator(HttpServletRequest request) {
        // 优先从请求头中获取用户名
        String username = request.getHeader("X-Username");
        
        // 如果请求头中没有，则尝试从其他请求头获取
        if (username == null || username.isEmpty()) {
            username = request.getHeader("X-Operator");
        }
        
        // 如果请求头中没有，则尝试从请求参数中获取
        if (username == null || username.isEmpty()) {
            username = request.getParameter("operatedBy");
        }
        
        // 如果都没有，则使用默认值
        if (username == null || username.isEmpty()) {
            username = "system";
        }
        
        return username;
    }

    @GetMapping("/profile")
    public ResponseEntity<User> getCurrentUserProfile(HttpServletRequest request) {
        try {
            String operatedBy = getOperator(request);
            
            Optional<User> userOpt = userService.findUserByUsername(operatedBy);
            if (userOpt.isPresent()) {
                User user = userOpt.get();
                
                // 创建副本，清除密码字段但保留所有其他信息（包括敏感信息）
                User profileUser = new User();
                profileUser.setId(user.getId());
                profileUser.setUsername(user.getUsername());
                profileUser.setName(user.getName());
                profileUser.setEmail(user.getEmail()); // 不脱敏
                profileUser.setPhone(user.getPhone()); // 不脱敏
                profileUser.setAge(user.getAge());
                profileUser.setGender(user.getGender());
                profileUser.setAddress(user.getAddress());
                profileUser.setRole(user.getRole());
                profileUser.setIsDelete(user.getIsDelete());
                profileUser.setStatus(user.getStatus());
                profileUser.setCreatedAt(user.getCreatedAt());
                profileUser.setUpdatedAt(user.getUpdatedAt());
                profileUser.setPassword(null); // 密码不返回
                
                return ResponseEntity.ok(profileUser);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            System.err.println("获取当前用户信息失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @PutMapping("/profile")
    public ResponseEntity<?> updateProfile(@RequestBody User userDetails, HttpServletRequest request) {
        try {
            String operatedBy = getOperator(request);
            
            // 获取当前用户信息
            User currentUser = userService.findUserByUsername(operatedBy)
                    .orElseThrow(() -> new RuntimeException("当前用户未找到"));
            
            // 只允许用户更新自己的信息
            User updatedUser = userService.updateUser(currentUser.getId(), userDetails, operatedBy);
            
            // 返回完整信息（不脱敏）
            updatedUser.setPassword(null);
            return ResponseEntity.ok(updatedUser);
            
        } catch (RuntimeException e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
}
